<?php

/**
 * tag标签对应文章等信息管理model操作
 * @author  xiaobai
 * @date    2018-01-17
 */

namespace app\common\model;

use app\common\model\Common;

class TagData extends Common
{
    protected $pk = 'id';

    const TYPE_NEWS = 1;    // 文章
    const TYPE_ASK  = 2;    // 问答
    const TYPE_DIVE = 3;    // 约潜潜点

    /**
     * 保存tag标签对应的数据信息
     * @param  array $tag_ids   tag标签id集
     * @param  int $data_id     内容id
     * @param  int $type        类型
     * @return array
     */
    public function setTagData($tag_ids = array(), $data_id = 0, $type = self::TYPE_NEWS)
    {
        $where   = array('data_id'=>$data_id, 'type'=>self::TYPE_ASK);
        $tag_del = $this->where($where)->delete();
        if ($tag_del === false) {
            return $this->result(1, '标签处理失败，请重新提交');
        }

        $tag_data = array();
        foreach ($tag_ids as $k=>$v) {
            $tag_data[$k]['tag_id']  = $v;
            $tag_data[$k]['data_id'] = $data_id;
            $tag_data[$k]['type']    = $type;
        }
        $tag_res = $this->saveAll($tag_data);
        if ($tag_res === false) {
            return $this->result(1, 'tag标签处理失败，请重新提交。');
        }
        return $this->result(0);
    }

    /**
     * 获取数据id对应的tag内容
     * @param int $data_id  数据id
     * @param int $type     类型，默认文章
     * @return array|false|mixed|\PDOStatement|string|\think\Collection
     */
    public function getTagData($data_id = 0, $type = self::TYPE_NEWS)
    {
        $where = array('a.data_id'=>$data_id, 'a.type'=>$type);
        $key   = 'getTagData_'.$data_id.'_'.$type;
        $lists = cache($key);
        if (empty($lists)) {
            $field = 'a.*, b.name, b.num';
            $lists = $this->field($field)->alias('a')->join('__TAG__ b', 'a.tag_id=b.id')->where($where)->select();
            if (!empty($lists)) {
                cache($key, $lists, 60*60*24);
            } else {
                $lists = array();
            }
        }
        return $lists;
    }

    /**
     * 删除获取文章tag标签的缓存
     * @param int $data_id
     * @param int $type
     */
    public function delGetTagDataCache($data_id = 0, $type = self::TYPE_NEWS)
    {
        $key = 'getTagData_'.$data_id.'_'.$type;
        cache($key, null);
    }
}
